import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from '../../utils/http';

const initialState = {
  list: [], //项目列表
  loading: false, //加载状态
};

export const getProjectListAsync = createAsyncThunk(
  'project/get_project_list',
  async () => {
    const response = await axios.get('/api/projects');
    return response.data;
  }
);

export const projectSlice = createSlice({
  name: 'project',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProjectListAsync.pending, (state, res) => {
        // console.log('pending', res);
        state.loading = true;
      })
      .addCase(getProjectListAsync.fulfilled, (state, res) => {
        // console.log('fulfilled', res);
        const data = res.payload.data.data;
        // console.log(data);

        data.forEach((element) => {
          if (typeof element.collect === 'undefined') {
            element.collect = false;
          }
        });
        state.list = data;
        state.loading = false;
      });
  },
});

export const {} = projectSlice.actions;

export const select_project_list = (state) => {
  return state.project.list;
};

export default projectSlice.reducer;
